package com.framework.common.exception;

import com.framework.common.Enums.FrameworkErrorCodeEnum;
import com.framework.common.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/12 17:28
 * @since JDK 1.8
 */
@Slf4j
public class Auth2ResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {
    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {

        if (e instanceof InsufficientAuthenticationException) {
            log.error("令牌失效！", e);
            return new ResponseEntity(R.error(FrameworkErrorCodeEnum.TOKEN_FAIL), HttpStatus.OK);
        }else if (e instanceof InvalidGrantException){
            log.error("refresh token失效！", e);
            return new ResponseEntity(R.error(FrameworkErrorCodeEnum.TOKEN_FAIL), HttpStatus.OK);
        }else if (e instanceof BusinessException) {
            log.error("用户不存在！", e);
            return new ResponseEntity(R.error(FrameworkErrorCodeEnum.USER_NOT_EXITS), HttpStatus.OK);
        } else {
            log.error("============自定义Auth2异常=========", e);
            return new ResponseEntity(R.error(FrameworkErrorCodeEnum.REFRESH_TOKEN_FAIL), HttpStatus.OK);
        }
       // return new ResponseEntity(R.error(ErrorCodeEnum.TOKEN_FAIL), HttpStatus.OK);
    }
}
